package com.wuyu.acl.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wuyu.acl.common.Result;
import com.wuyu.acl.po.AdminRole;
import com.wuyu.acl.po.Role;
import com.wuyu.acl.service.AdminRoleService;
import com.wuyu.acl.service.RoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Tag(name = "用户角色管理")
@RestController
@RequestMapping("/admin/acl/admin_role")
public class AdminRoleController {

    @Resource
    private AdminRoleService adminRoleService;

    @Resource
    private RoleService roleService;

    /**
     * 用户角色管理：通过用户id获取该用户的所有角色信息
     *
     * @param userId
     * @return
     */
    @Operation(summary = "通过用户id获取该用户的所有角色信息")
    @GetMapping("/{userId}")
    public Result getRolesByUserId(@PathVariable("userId") Long userId) {
        List<AdminRole> adminRoleList = adminRoleService.list(new LambdaQueryWrapper<AdminRole>()
                .eq(AdminRole::getAdminId, userId));
        // 如果该用户没有角色，直接返回空数组
        if (CollUtil.isEmpty(adminRoleList)) {
            return Result.ok(CollUtil.newArrayList());
        }
        List<Long> roleIdList = adminRoleList.stream().map(AdminRole::getRoleId).collect(Collectors.toList());
        List<Role> roleList = roleService.listByIds(roleIdList);
        return Result.ok(roleList);
    }

    /**
     * 用户角色管理：为用户分配角色
     *
     * @param userId
     * @param roleIds
     * @return
     */
    @Operation(summary = "为用户分配角色")
    @Transactional
    @PostMapping("/{userId}")
    public Result add(@PathVariable("userId") Long userId,
                      @RequestBody List<Long> roleIds) {
        // 1. 删除用户原有的角色信息
        adminRoleService.remove(new LambdaQueryWrapper<AdminRole>()
                .eq(AdminRole::getAdminId, userId));
        List<AdminRole> adminRoleList = roleIds.stream().map(roleId -> {
            AdminRole adminRole = new AdminRole();
            adminRole.setAdminId(userId);
            adminRole.setRoleId(roleId);
            return adminRole;
        }).collect(Collectors.toList());
        // 2. 添加用户新的角色信息
        adminRoleService.saveBatch(adminRoleList);
        return Result.ok();
    }
}
